<?php
#等级权益配置修改后，品牌等级
use Biz\model\brand\Brand as mBrand;
use Biz\pockets\constInterface\BrandLevel as IBrandLevel;
use Biz\service\BrandRights\BrandLevelRightsConfigService;
use Biz\service\BrandRights\BrandRightsSourceService;

ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';
ini_set('memory_limit', '1024M');

$level = $argv[1];
$rightsName = $argv[2];

if (!isset(IBrandLevel::BRAND_LEVELS[$level])) {
    exitEcho("level:{$level} error!");
}

$sourceRightsId = BrandRightsSourceService::getIdByRightsName($rightsName);

if (!$sourceRightsId) {
    exitEcho("rightsName:{$rightsName} error!");
}

//查询等级权益配置
$levelRightsCfg = BrandLevelRightsConfigService::getLevelOneRightsConfig($level, $sourceRightsId);
if ($levelRightsCfg) {
    $rightsNum = $levelRightsCfg['rights_data'];
    $rightsStatus = $levelRightsCfg['status'];
} else {
    exitEcho('当前等级' . IBrandLevel::BRAND_LEVELS[$level] . '没有配置权益：' . $rightsName);
}
if (!in_array($rightsStatus, [1, 9])) {
    exitEcho("rightsStatus:{$rightsStatus} error!");
}

updateBrandLevelRights($level, $rightsName, $sourceRightsId, $rightsNum, $rightsStatus);

exitEcho('finish');

function updateBrandLevelRights(int $level, string $rightsName, int $sourceRightsId, int $rightsNum, int $rightsStatus)
{
    $rightsType = BrandRightsSourceService::getRightsTypeById($sourceRightsId);
    $page = 1;
    $pageSize = 100;
    $data['level'] = $level;
    $data['rights_source_id'] = $sourceRightsId;
    $data['rights_num'] = $rightsNum;
    $data['rights_status'] = $rightsStatus;
    $data['rights_type'] = $rightsType;
    var_dump('更新权益' . $rightsName, $data);

    $where = [
        'uid[>]' => 0,
        'level' => $level
    ];
    $brandCount = mBrand::count($where);
    var_dump('查询到等级「Lv' . $level . '」的品牌数：' . $brandCount);
    do {
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where['LIMIT'] = $limit;
        $brands = mBrand::selectByWhere($where, ['id', 'uid', 'level']);
        foreach ($brands as $brand) {
            $data['brand'] = $brand;
            var_dump('更新等级「Lv' . $level . '」权益「' . $rightsName . '(' . $sourceRightsId . ')」的品牌id:' . $brand['id']);
            list($result, $msg) = BrandLevelRightsConfigService::changeConfig($data);
            var_dump('更新结果#result:' . $result . '#message:' . $msg);
        }
        $page++;
    } while (!empty($brands));
}

function exitEcho(string $msg)
{
    echo $msg;
    exit;
}